const express = require('express');
const multer = require('multer');
const path = require('path');

const router = express.Router();

// 配置上传目录和文件名
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // 上传到项目根目录下的 uploads 文件夹
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
    const ext = path.extname(file.originalname);
    cb(null, file.fieldname + '-' + uniqueSuffix + ext);
  },
});

const upload = multer({ storage });

// 上传接口
router.post('/api/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ message: '没有文件上传' });
  }

  // 返回文件的访问路径
  res.json({ url: `/uploads/${req.file.filename}` });
});

module.exports = router;
